﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// ChooseUser.xaml 的交互逻辑
    /// </summary>
    public partial class ChooseUser : Window, INotifyPropertyChanged
    {
        public ChooseUser()
        {
            InitializeComponent();
            this.DataContext = this;            
        }
        public bool IsSelected = false;//指示当前是否需要筛选试卷
        Task select;
        ListenToFuzzyQuery fuzzyQuery;//试卷筛选类
        CancellationTokenSource tokenSource;
        CancellationToken cancellationToken;//取消筛选试卷线程
        #region UserList
        private List<UserInfoModel> m_UserList = new List<UserInfoModel>();

        public List<UserInfoModel> UserList
        {
            get
            {
                return this.m_UserList;
            }
            set
            {
                this.m_UserList = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region SelectedUser
        private UserInfoModel m_SelectedUser;

        public UserInfoModel SelectedUser
        {
            get
            {
                return this.m_SelectedUser;
            }
            set
            {
                this.m_SelectedUser = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region SelectedTestPaper
        private PaperModel m_SelectedTestPaper;

        public PaperModel SelectedTestPaper
        {
            get
            {
                return this.m_SelectedTestPaper;
            }
            set
            {
                this.m_SelectedTestPaper = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region PaperList
        private List<PaperModel> m_PaperList = new List<PaperModel>();

        public List<PaperModel> PaperList
        {
            get
            {
                return this.m_PaperList;
            }
            set
            {
                this.m_PaperList = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region INotifyPropertyChanged 接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName]string propName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
        #endregion
        /// <summary>
        /// 生成试卷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedUser == null)
            {
                MessageBox.Show("请选择选手！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            if (this.SelectedTestPaper == null)
            {
                MessageBox.Show("请选择试卷！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            MainWindowNew.ChooseUser = this.SelectedUser;
            MainWindowNew.ChooseTestPaper = this.SelectedTestPaper;
            this.DialogResult = true;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //List<UserInfoModel> userList = UserInfoDAL.SelectUserList();
            //userList.ForEach(p => this.UserList.Add(new UserViewModel(p)));
            //List<TestPaperModel> paperList = TestPaperDAL.SelectTestPaperList();
            //paperList.ForEach(p => this.PaperList.Add(new TestPaperViewModel(p)));
            tokenSource = new CancellationTokenSource();
            cancellationToken = tokenSource.Token;
            fuzzyQuery = new ListenToFuzzyQuery();
            fuzzyQuery.OnFuzzyQuery += UpdateQueryResult;
            this.UserList = UserInfoDAL.SelectUserList();
            this.PaperList = PaperDAL.SelectTestPaperList(false);
            select = Task.Run(() =>
                {
                while (true)
                {
                        if(tokenSource.IsCancellationRequested)
                        {
                            break;
                        }
                        while(IsSelected)
                        {
                            try
                            {
                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    if (this.KeyTextBox.Text == "")
                                    {
                                        this.PaperList = PaperDAL.SelectTestPaperList(false);
                                    }
                                    else
                                    {
                                        fuzzyQuery.KeyText = this.KeyTextBox.Text;
                                        this.PaperList = fuzzyQuery.QueryList;
                                    }
                                }));
                            }
                            catch (Exception ex)
                            {

                            }
                            Thread.Sleep(600);

                        }
                    }
                        
                },cancellationToken);
        }

        private List<PaperModel> UpdateQueryResult(string keytext)
        {
            string sql = "select * from paper where `Describe` like '%" + keytext + "%'";
            DataSet ds = DbHelper.ExecuteDataset(sql);
            List<PaperModel> lst = new List<PaperModel>();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    PaperModel info = new PaperModel();
                    info.Id = Convert.ToInt32(dt.Rows[i]["Id"].ToString());
                    info.Describes = dt.Rows[i]["Describes"].ToString();
                    info.TesQuestiontList = dt.Rows[i]["TesQuestiontList"].ToString();
                    info.TotalScore = decimal.Parse(dt.Rows[i]["TotalScore"].ToString());
                    if (!(dt.Rows[i]["CreateTime"] is DBNull))
                        info.CreateTime = DateTime.Parse(dt.Rows[i]["CreateTime"].ToString());
                    if (!(dt.Rows[i]["UpdateTime"] is DBNull))
                        info.UpdateTime = DateTime.Parse(dt.Rows[i]["UpdateTime"].ToString());
                    lst.Add(info);
                }
            }
            return lst;
        }

        private void KeyTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            this.IsSelected=true;
            this.combolevel.SelectedItem = null;
        }

        private void KeyTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            this.IsSelected = false;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {            
            if (combolevel.SelectedItem != null && combolevel.SelectedItem.ToString().Substring(38, 1) == "全")
            {
                this.PaperList.Clear();
                this.PaperList = PaperDAL.SelectTestPaperList(false);               
                //foreach (var model in QueryPaperList)
                //{
                //    if (this.PaperList.Where(p => p.TestPaperID == model.TestPaperID).Count() == 0)
                //        this.PaperList.Add(new TestPaperViewModel(model));
                //}
            }
            else if (combolevel.SelectedItem != null && combolevel.SelectedItem.ToString().Substring(38, 1) == "无")
            {
                this.PaperList.Clear();
                this.PaperList = PaperDAL.GetTestPaperByLevel("");               
                //foreach (var model in QueryPaperList)
                //{
                //    if (this.PaperList.Where(p => p.TestPaperID == model.TestPaperID).Count() == 0)
                //        this.PaperList.Add(new TestPaperViewModel(model));
                //}
            }
            else if (combolevel.SelectedItem != null)
            {
                this.PaperList.Clear();
                this.PaperList = PaperDAL.GetTestPaperByLevel(combolevel.SelectedItem.ToString().Substring(38, 1));                
                //foreach (var model in QueryPaperList)
                //{
                //    if (this.PaperList.Where(p => p.TestPaperID == model.TestPaperID).Count() == 0)
                //        this.PaperList.Add(new TestPaperViewModel(model));
                //}
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            //select.Dispose();
            tokenSource.Cancel();//取消筛选试卷的Task
        }
    }
    public class ListenToFuzzyQuery
    {
        public List<PaperModel> QueryList;
        private string m_keyText="";
        public string KeyText
        {
            get { return m_keyText; }
            set
            {
                if (value != m_keyText)
                {
                    m_keyText = value;
                    KeyTextChange();
                }
                
            }
        }
        public delegate List<PaperModel> FuzzyQueryEventHandler(string Keytext);
        public event FuzzyQueryEventHandler OnFuzzyQuery;
        //触发事件
        public void KeyTextChange()
        {
            if (OnFuzzyQuery != null)
            {
                QueryList = OnFuzzyQuery(this.KeyText);
            }
        }
    }
    
}
